import ENV from './config/config.js';
import Local from '../library/utils/storage.js';
export async function uploadFile(url, filePath) {
	const userInfo = Local.GetUserInfo();
	const Authorization = userInfo && userInfo.token ? `Bearer ${userInfo.token}` : "";
	// console.log('sss',filePath)
	let _filePath =filePath;
		// console.log(filePath)
	let info = await GetImageInfo(filePath);
	if(info){
		//压缩
		let com = await CompressImage(filePath,info);
			// console.log(info,com)
		if(com){
			_filePath = com;
			
		}
	}
	// console.log(_filePath)


	return new Promise((reslove, reject) => {
		let uploadTask = uni.uploadFile({
			header: {
				Authorization
			},
			url: ENV.BASE_URL + url,
			name: "file",
			filePath:_filePath,
			success(res) {
				console.log('uploadFile', res);
				if (res && 200 == res.statusCode) {
					if (res.data) {
						let data = JSON.parse(res.data);
						if (data && data.data) {
							reslove(data);
						}
					}
				} else {
					reslove(false);
				}

			},
			fail(e) {
				console.log('uploadFile Error', e);
				reslove(false);
			}


		});

		uploadTask.onProgressUpdate((res) => {
			console.log('上传进度' + res.progress);
			console.log('已经上传的数据长度' + res.totalBytesSent);
			console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);
			// 测试条件，取消上传任务。
			if (res.progress >= 100) {
				// uploadTask.abort();
				// reslove(true)
			}
		});
	})
}

function GetImageInfo(src) {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src,
			success(res) {
				resolve(res);
			},
			fail() {
				resolve(false);
			}
		})
	});
}

function CompressImage(src,info) {
	const maxResolution = 1000;
	let w = info.width;
	let h = info.height;
	if (w > h) {
		if (w > maxResolution) {
			h *= maxResolution / w;
			w = maxResolution;
		}
	} else {
		if (h > maxResolution) {
			w *= maxResolution / h;
			h = maxResolution;
		}
	}
	console.log('压缩后宽高：',w,h)
	return new Promise((resolve, reject) => {
		uni.compressImage({
			src,
			quality: 80,
			compressedHeight:h,
			compressedWidth:w,
			success(res) {
				resolve(res.tempFilePath);
			},
			fail(err){
				console.log('压缩失败:',err)
				resolve(src);
			}
		})
	})
}